package com.yfve.eol.receiver;

import android.car.hardware.CarPropertyValue;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import com.yfve.eol.EolHandler;

public class InterTestReceiver extends BroadcastReceiver {

    private static final String TAG = "InterTestReceiver";

    private static final String ACTION_EOL_INTER_TEST = "com.yfve.eol.action.INTER_TEST";
    private static final String EXTRA_INTER_TEST_CMD_ID = "com.yfve.eol.INTER_TEST.CMD_ID";
    private static final String EXTRA_INTER_TEST_CMD_VALUE_ARRAY = "com.yfve.eol.INTER_TEST.CMD_VALUE_ARRAY";

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i(TAG, "onReceive: ");
        String action = intent.getAction();
        if (action != null && action.equals(ACTION_EOL_INTER_TEST)) {
            int cmdId = intent.getIntExtra(EXTRA_INTER_TEST_CMD_ID, -1);

            String cmdValueArrayString = intent.getStringExtra(EXTRA_INTER_TEST_CMD_VALUE_ARRAY);
            if (TextUtils.isEmpty(cmdValueArrayString)) {
                cmdValueArrayString = "1";
            }
            String[] cmdValueArrayValue = cmdValueArrayString.split(",");
            Log.i(TAG, "onReceive: cmdId = " + cmdId + ", cmdValueArrayString = " + cmdValueArrayString + " , split into part: " + cmdValueArrayValue.length);

            Message msg = EolHandler.getEolHandler().obtainMessage();
            byte[] valueBytes;
            valueBytes = new byte[cmdValueArrayValue.length];
            for (int i = 0; i < cmdValueArrayValue.length; i++) {
                int val = Integer.parseInt(cmdValueArrayValue[i].replaceAll("^0[x|X]", ""), 16);
                valueBytes[i] = (byte) val;
            }

            CarPropertyValue<byte[]> carPropertyValue = new CarPropertyValue<>(cmdId, 0, valueBytes);

            msg.what = EolHandler.MSG_EOL;
            msg.obj = carPropertyValue;
            EolHandler.getEolHandler().sendMessage(msg);
        }
    }
}
